package net.javalib.flickr.search.activities;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.List;

import net.javalib.flickr.search.DownloadInfo;
import net.javalib.flickr.search.FlickrSearchApplication;
import net.javalib.flickr.search.flickr.FlickrImage;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

/**
 * Class containing boiler-plate activity related stuff.
 * Most activities in this application extend this.
 */
public class AbstractBaseActivity extends Activity {
	public FlickrSearchApplication app;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		app = (FlickrSearchApplication) getApplication();
        Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(Thread.getDefaultUncaughtExceptionHandler()));
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		app.setCurrentActivity(this);
	}
	
	@Override
	protected void onPause() {
		app.setCurrentActivity(null);
		super.onPause();
	}
	
	// CALLBACKS
	// Subclasses can choose what notifications they need and then override the 
	// appropriate method below.
	public void searchError(Exception e) {}
	public void searchStarted(String term) {}
	public void searchResult(List<FlickrImage> images) {}
	public void searchDone() {}
	public void bitmapDownloaded(DownloadInfo request) {}
	public void setSearchProgress(int value) {}
	public void onProgress(FlickrImage image, int percentage) {}
	
	// ------------
	// GENERAL
	// ------------
	
	protected void showKeyboard(boolean show, View view) {
		InputMethodManager imm = (InputMethodManager)(getSystemService(Context.INPUT_METHOD_SERVICE));
		if (show) {
			imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
		} else {
			imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
		}
	}
	
}

//-----------------------
//EXCEPTION HANDLING
//-----------------------

class ExceptionHandler implements UncaughtExceptionHandler {
	UncaughtExceptionHandler defaultHandler;

	public ExceptionHandler(UncaughtExceptionHandler defaultHandler) {
		this.defaultHandler = defaultHandler;
	}
	
	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		ex.printStackTrace();
		defaultHandler.uncaughtException(thread, ex);
	}	
}
